﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using DICOM_PROJECT.Models;
using DICOM_PROJECT.DAL;
using System.Web.Security;
using System.Security.Principal;
using DICOM_PROJECT.DAL.Security;
using Newtonsoft.Json;
using System.Web.Script.Serialization;
using System.Collections;

namespace DICOM_PROJECT.Controllers
{
    public class UserProfileController : BaseController
    {
        // GET: /UserProfile/
        //[Authorize]
        public ActionResult Index()
        {
            return View(db.UserProfiles.ToList());
        }

        //public ActionResult Login()
        //{
        //    return View();
        //}

        [HttpPost]
        public ActionResult Login(LoginModel login)
        {
            if(ModelState.IsValid)
            {
                UserProfile user = null;
                try
                {
                    user = db.UserProfiles.FirstOrDefault(u => u.UserProfileID == login.ID && u.Password == login.Password);
                }
                catch(Exception e)
                {
                    ModelState.AddModelError("", "System can't access database!");
                    return View("_Login");
                }

                if(user!=null)
                {
                    CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel();
                    serializeModel.UserID = user.UserProfileID;
                    serializeModel.Name = user.Name;
                    serializeModel.UserType = user.UserType;
                    serializeModel.Roles = user.Roles.Select(r => r.RoleName).ToList();

                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    string userData = serializer.Serialize(serializeModel);

                    //string userData = JsonConvert.SerializeObject(serializeModel);
                    FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, user.UserProfileID.ToString(), DateTime.Now, DateTime.Now.AddMinutes(2880), false, userData);
                    string encryptTicket = FormsAuthentication.Encrypt(authTicket);
                    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptTicket);
                    Response.Cookies.Add(cookie);
                    //Radiologist
                    if(serializeModel.UserType=="Radiologist")
                    {
                        HttpContext.Session.Add("dicomImage", null);
                    }
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", "Invalid ID or Password");
                }
            }
            return View("_Login");
            //return RedirectToAction("Index", "Home");//khong bao loi
        }

        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }

        // GET: /UserProfile/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            UserProfile userprofile = db.UserProfiles.Find(id);
            if (userprofile == null)
            {
                return HttpNotFound();
            }
            return View(userprofile);
        }

        // GET: /UserProfile/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: /UserProfile/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include="UserProfileID,Password,SocialID,Name,Birthday,Male,Address,Phone,UserType")] UserProfile userprofile)
        {
            if (ModelState.IsValid)
            {
                db.UserProfiles.Add(userprofile);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(userprofile);
        }

        // GET: /UserProfile/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            UserProfile userprofile = db.UserProfiles.Find(id);
            if (userprofile == null)
            {
                return HttpNotFound();
            }
            return View(userprofile);
        }

        // POST: /UserProfile/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include="UserProfileID,Password,SocialID,Name,Birthday,Male,Address,Phone,UserType")] UserProfile userprofile)
        {
            if (ModelState.IsValid)
            {
                db.Entry(userprofile).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(userprofile);
        }

        // GET: /UserProfile/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            UserProfile userprofile = db.UserProfiles.Find(id);
            if (userprofile == null)
            {
                return HttpNotFound();
            }
            return View(userprofile);
        }

        // POST: /UserProfile/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            UserProfile userprofile = db.UserProfiles.Find(id);
            db.UserProfiles.Remove(userprofile);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
